---
// 标签组件
import { getCollection } from 'astro:content';
import { processFrontmatter } from '../../integrations/process-frontmatter';

const { tags = [] as string[] } = Astro.props;

// 获取所有文章并统计标签数量
const allPosts = await getCollection('posts');
const processedPosts = await Promise.all(allPosts.map(post => processFrontmatter(post)));

// 统计所有标签的文章数量
const tagCounts = new Map<string, number>();
processedPosts.forEach(post => {
  const postTags = post.data.tags || [];
  postTags.forEach((tag: string) => {
    if (tag && tag.trim()) {
      tagCounts.set(tag, (tagCounts.get(tag) || 0) + 1);
    }
  });
});

import '../../styles/components/others/Tags.styl';
---

<!-- 文章标签部分 -->
<div class="sidebar-section tags">
  <div class="section-header">
    <h3>文章标签</h3>
    <button id="tags-toggle" class="section-toggle" aria-label="折叠标签">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18">
        <path fill="currentColor" d="M7 10l5 5 5-5z"></path>
      </svg>
    </button>
  </div>  <div id="tags-content" class="section-content">
    <div class="tag-cloud">
      {tags && tags.length > 0 ? (
        tags.map((tag: string) => (
          <a href={`/tags/${tag}/`} class="tag">
            <span class="tag-name">{tag}</span>
            <span class="tag-count">({tagCounts.get(tag) || 0})</span>
          </a>
        ))
      ) : (
        <div class="no-tags">暂无标签</div>
      )}
    </div>
  </div>
</div>

<script>
  // 标签折叠/展开功能
  document.addEventListener('DOMContentLoaded', () => {
    const toggleBtn = document.getElementById('tags-toggle');
    const contentEl = document.getElementById('tags-content');
    
    if (toggleBtn && contentEl) {
      toggleBtn.addEventListener('click', () => {
        const isCollapsing = !contentEl.classList.contains('collapsed');
        
        if (isCollapsing) {
          // 快速折叠 (250ms)
          contentEl.style.transition = 'max-height 0.25s ease, opacity 0.25s ease';
        } else {
          // 缓慢展开 (600ms)
          contentEl.style.transition = 'max-height 0.6s ease, opacity 0.6s ease';
        }
        
        contentEl.classList.toggle('collapsed');
        toggleBtn.classList.toggle('collapsed');
      });
    }
  });
</script>